//
//  TJOAuthViewController.swift
//  WeiBo
//
//  Created by TanJian on 15/12/7.
//  Copyright © 2015年 Joshpell. All rights reserved.
//

import UIKit
import SVProgressHUD

let TJSwitchController = "TJSwitchController"

let WB_APPKEY = "1663643297"
let WB_APPSECRET = "6b0105398380e867d2eb45342dcd84ff"
let WB_REDIRECTURI = "http://www.baidu.com"


class TJOAuthViewController: UIViewController , UIWebViewDelegate {

    lazy var webView = UIWebView()

    //加载本页视图
    override func loadView() {
        super.loadView()
        
        webView.delegate = self
        view = webView
        setupUI()
    }
    
    
    //加载网络页面
    override func viewDidLoad() {
        super.viewDidLoad()
        
        webView.loadRequest(NSURLRequest(URL: NSURL(string:"https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REDIRECTURI)")!))
    }
    
    
    
    
    func setupUI(){
        title = "新浪微博"
        
        //navbar标题设置
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancle")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFill")
    }
    
    
    
    @objc private func autoFill() {

        let jsStr = "document.getElementById('userId').value='17710652124';document.getElementById('passwd').value='58722419tj'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsStr)
    }

    
    
    @objc private func cancle() {
        //nav的子控制器用pop，另外的控制器用dismiss
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    

    //webview的代理方法，加载webview时调用
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }

    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        
        SVProgressHUD.dismiss()
        
    }

    //代理方法检查回调数据
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        
        print("--------\(urlString)")
        
        //如果webview页面不是以回调页加载，返回true，继续继承加载
        if !urlString.hasPrefix(WB_REDIRECTURI){
            return true
        }
        print(request.URL!.query)
        if let query = request.URL!.query where query.hasPrefix("code="){
            //拿到授权码,获取Token值
            let code = query.substringFromIndex("code=".endIndex)
            
            TJUserAcountViewModel.shareViewModel.loadAccessToken(code, complete: { (isSuccess) -> () in
                
                if !isSuccess {
                    print("AccessToken加载失败")
                    SVProgressHUD.showErrorWithStatus("AccessToken加载失败")
                    return
                }
                //加载成功关闭当前页面
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    NSNotificationCenter.defaultCenter().postNotificationName(TJSwitchController, object: self)
                print("AccessToken加载成功")
            })

            
            })

            
        }else{
            print("取消授权")
            dismissViewControllerAnimated(true, completion: nil)
        }

        return true
    }
    
    

    
}




